package com.stylefeng.guns.modular.netcar.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.model.CommonKeyValue;
import com.stylefeng.guns.core.model.Pager;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.netcar.dao.DriverInfMapper;
import com.stylefeng.guns.modular.netcar.model.DispatchPsnDriver;
import com.stylefeng.guns.modular.netcar.model.DriverInf;
import com.stylefeng.guns.modular.netcar.service.IDispatchPsnCarService;
import com.stylefeng.guns.modular.netcar.service.IDispatchPsnDriverService;
import com.stylefeng.guns.modular.netcar.service.IDriverInfService;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.modular.netcar.service.ILineRangePriceService;
import com.stylefeng.guns.modular.system.model.Org;
import com.stylefeng.guns.modular.system.service.IOrgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**

 * 驾驶员信息 Service 实现 
 * @author sasazaixian
 * @Date 2018-10-23 11:06
 */
@Service
public class DriverInfServiceImpl extends ServiceImpl<DriverInfMapper,DriverInf> implements IDriverInfService {

    @Resource
    private DriverInfMapper driverInfMapper;
    @Autowired
    private IDispatchPsnDriverService dispatchPsnDriverService;
    @Autowired
    private IOrgService orgService;
    /**
     * 删除驾驶员信息
     * @param driverInf
     * @return     
     */
    @Transactional
    public int deleteDriverInf(DriverInf driverInf,String token)throws Exception{
        if(driverInf==null ){
            throw new RuntimeException("参数不全！");
        }
        List<DriverInf> listDriver=driverInfMapper.selectListDriverInf(driverInf);
        for(DriverInf en:listDriver){
            DispatchPsnDriver dispatchPsnDriver=new DispatchPsnDriver();
            dispatchPsnDriver.setDiId(en.getDiId());
            List list=dispatchPsnDriverService.selectListDispatchPsnDriver(dispatchPsnDriver,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在调度指派驾驶员中使用，不能删除！");
            }
        }
        return this.driverInfMapper.deleteDriverInf(driverInf);
    }
    /**
     * 批量删除驾驶员信息
     * @param ids 主键ID数组
     * @return 
     */
    @Transactional
    public int deleteBatchDriverInf(String[] ids,String token)throws Exception{
        for(String id:ids){
            DispatchPsnDriver dispatchPsnDriver=new DispatchPsnDriver();
            dispatchPsnDriver.setDiId(id);
            List list=dispatchPsnDriverService.selectListDispatchPsnDriver(dispatchPsnDriver,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在调度指派驾驶员中使用，不能删除！");
            }

        }
        return this.driverInfMapper.deleteBatchDriverInf(ids);
    }
    /**
     * 查询驾驶员信息列表
     * @param driverInf 驾驶员信息对象
     * @return
     */
    public List<DriverInf> selectListDriverInf(DriverInf driverInf,String token)throws Exception{
        return  this.driverInfMapper.selectListDriverInf(driverInf);
    }
    /**
	 * 分页查询驾驶员信息列表
     * @param pager 分页对象
     * @return
     */     
    public  Map pageListDriverInf(Pager pager,String token) throws Exception{
        Page page=new Page(pager.getPageNumber(),pager.getPageSize());
        page.setRecords(driverInfMapper.selectListDriverInf(page,(DriverInf)pager.getObj()));
        List<DriverInf> list = page.getRecords();
        Map mapDate = new HashMap();
        mapDate.put("rows", list);
        mapDate.put("total", page.getTotal());
        mapDate.put("page", page.getCurrent());
        mapDate.put("pageCount", page.getPages());
        return mapDate;
    }
    /**
     * 同一个事务 互斥锁查询
     * @param driverInf 驾驶员信息对象
     * @return 
     */
    public  List<DriverInf> selectListDriverInfForUpdate(DriverInf driverInf)throws Exception{
        return  this.driverInfMapper.selectListDriverInfForUpdate(driverInf);
    }
    /**
     * 通过主键id查询的驾驶员信息列表
     * @param id 主键id
     * @return     
     */
    public  DriverInf findDriverInfById(String id,String token)throws Exception{
        return  this.driverInfMapper.findDriverInfById(id);
    }

    /**
     * 新增驾驶员信息数据
     * @param driverInf  驾驶员信息对象
     * @return
     */
    @Transactional
    public int insertDriverInf(DriverInf driverInf,String token) throws Exception { 
        if(driverInf!=null && (driverInf.getDiId()==null || driverInf.getDiId().trim().length()<10)){
            driverInf.setDiId(IdWorker.get32UUID());
        }
        if(driverInf.getDiDeptId()==null || driverInf.getDiDeptId().trim().length()<1){
            throw new RuntimeException("所属车队不能为空！");
        }
        //通过车队找到所属公司id
        String deptId=driverInf.getDiDeptId();
        //根据所属车队找到所属机构ID
        Org org=new Org();
        org.setSoId(Integer.parseInt(deptId));
        org=orgService.selectOne(new EntityWrapper<>(org));
        if(org==null ){
            throw new RuntimeException("所属车队不存在！");
        }
        if(org.getSoType().equals("1")){
            driverInf.setSoId(deptId);
        }else{
            Integer pid=org.getSoPid();
            BB:
            while(true){
                if(pid!=null){
                    Org porg=this.orgService.selectById(pid);
                    if(porg!=null){
                        if(StringUtils.equals("1",porg.getSoType())){
                            driverInf.setSoId(""+porg.getSoId());
                            break;
                        }else{
                            pid= porg.getSoPid();
                            continue BB;
                        }
                    }
                }
                break;
            }
        }

        String phone=driverInf.getDiPhone();
        String salt=ShiroKit.getRandomSalt(5);
        driverInf.setDiSalt(salt);
        driverInf.setDiPassword(ShiroKit.md5(StringUtils.substring(StringUtils.trimToNull(phone),-6), salt));
        return  this.driverInfMapper.insertDriverInf(driverInf);
    }
    
    /**
     * 更新驾驶员信息数据
     * @param driverInf 驾驶员信息对象
     * @return     
     */
    @Transactional
    public int updateDriverInf(DriverInf driverInf,String token) throws Exception {
        if(driverInf.getDiDeptId()!=null && driverInf.getDiDeptId().trim().length()>0) {
            //通过车队找到所属公司id
            String deptId = driverInf.getDiDeptId();
            //根据所属车队找到所属机构ID
            Org org = new Org();
            org.setSoId(Integer.parseInt(deptId));
            org = orgService.selectOne(new EntityWrapper<>(org));
            if (org == null) {
                throw new RuntimeException("所属车队不存在！");
            }
            if (org.getSoType().equals("1")) {
                driverInf.setSoId(deptId);
            } else {
                Integer pid=org.getSoPid();
                BB:
                while(true){
                    if(pid!=null){
                        Org porg=this.orgService.selectById(pid);
                        if(porg!=null){
                            if(StringUtils.equals("1",porg.getSoType())){
                                driverInf.setSoId(""+porg.getSoId());
                                break;
                            }else{
                                pid= porg.getSoPid();
                                continue BB;
                            }
                        }
                    }
                    break;
                }
            }
        }
        return  this.driverInfMapper.updateDriverInf(driverInf);
    }

    @Override
    public int updatePsw(String id, String token) throws Exception {
        DriverInf driverInf=this.findDriverInfById(id,token);
        if(driverInf==null || driverInf.getDiId()==null || driverInf.getDiId().trim().length()<10){
             throw new RuntimeException("驾驶员不存在！");
        }
        String phone=driverInf.getDiPhone();
        String salt=driverInf.getDiSalt();
        DriverInf updateDriverInf=new DriverInf();
        updateDriverInf.setDiId(id);
        updateDriverInf.setDiPassword(ShiroKit.md5(StringUtils.substring(StringUtils.trimToNull(phone),-6), salt));
        updateDriverInf(updateDriverInf,token);
        return 0;
    }

    /**
     * 查询驾驶员信息返回key-Value属性
     * @param driverInf 系统操作对象
     * @return     
     */
    public List<CommonKeyValue> optionsDriverInf(DriverInf driverInf,String token) throws Exception {
        List<DriverInf> listDriverInf=this.driverInfMapper.selectListDriverInf(driverInf);
        List<CommonKeyValue> listOptions=new ArrayList<CommonKeyValue>();
        for(DriverInf item:listDriverInf){
            CommonKeyValue opts=new CommonKeyValue();
            opts.setId(""+item.getDiId());
            opts.setValue(item.getDiName());
            listOptions.add(opts);
        }
        return listOptions;
    }

    @Override
    public DriverInf findDriverInfForUpdate(String id) throws Exception {
        return this.driverInfMapper.findDriverInfForUpdate(id);
    }

    @Transactional
    @Override
    public int updateDriverInfTaskNum(String diId,int taskNum) throws Exception {
        DriverInf selDriverInf=this.findDriverInfForUpdate(diId);
        if(selDriverInf==null){
            throw new RuntimeException("驾驶员未找到！");
        }
        if(taskNum<0 && selDriverInf.getDiTaskNum()<(-1*taskNum)){
            selDriverInf.setDiTaskNum(-1*selDriverInf.getDiTaskNum());
        }else{
            selDriverInf.setDiTaskNum(taskNum);
        }
        this.driverInfMapper.updateDriverInfTaskNum(selDriverInf);
        return 0;
    }
}
